<!--
 * @Description: 
 * @Author: Binggan
 * @Date: 2019-03-21 19:20:45
 * @LastEditors: Binggan
 * @LastEditTime: 2020-03-04 16:01:41
 -->
<template>
    <div class="content-wrap">
        <div class="manager-box">
            <Button type="primary" size='large' @click="toAddUser">添加新用户</Button>
            <!-- <Upload action="/" style="display:inline-block;vertical-align: top;" :on-success="uploadOk" :on-error="uploadFail" accept='.csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'>
                <Button icon="ios-cloud-upload-outline" type="success" size='large'>批量添加新用户</Button>
            </Upload> -->
        </div>
        
        <!-- 用户列表 -->
        <Table :data="data1" :columns="tableColumns" stripe border class="m-t-30">
            <template slot-scope="{ row, index }" slot="education">
              <span>{{educationArr[row.userEducation-1]}}</span>
            </template>
            <template slot-scope="{ row, index }" slot="operate">
                <Button type="primary" size="small" style="margin-right: 5px" @click="toAmend(row)">修改</Button>
                <Button type="error" size="small" @click="deleteUser(row)">删除</Button>
                <!-- <Button type="error" size="small" @click="resetPwd(row)">重置密码</Button> -->
            </template>
        </Table>
        <!-- 分页 -->
        <mPagination :count="count" :page="page" :pageSize="pageSize" @page-change="changePage"></mPagination>

        <!-- 用户添加修改 -->
        <Modal v-model="modal1" :title="isAdd?'用户添加':'信息修改'"  :mask-closable="false" class-name="bing-modal"><!--@on-ok="amend" @on-cancel="cancAmend"-->
           <Form ref="formUserInfo" :model="currentuser" :rules="ruleValidate" :label-width="80">
              <FormItem label="用户名称" prop="username">
                  <Input v-model="currentuser.username"></Input>
              </FormItem>
              <FormItem label="手机号码" prop="phone">
                  <Input v-model="currentuser.phone"></Input>
              </FormItem>
              <FormItem label="角色">
                  <Select v-model="currentuser.roleId">
                        <Option v-for='(item,index) in roles' :key='index' :value="item.id">{{item.name}}</Option>
                  </Select>
              </FormItem>
          </Form>
              <div slot="footer">
                  <Button type="text" size="large" @click="cancAmend">取消</Button>
                  <Button type="primary" size="large" :loading="amendLoading" @click="amend">确认{{isAdd?'添加':'修改'}}</Button>
              </div>
        </Modal>

         <!-- 删除对话框 -->
        <Modal v-model="modal2">
            <p slot="header" style="color:#f60">
                <Icon type="ios-information-circle"></Icon>
                <span>删除确认</span>
            </p>
            <div style="font-size:14px">
                <p style="color:#000">请确认是否删除这个用户?</p>
                <ul class="department-delinfo">
                  <li><span class="title">用户名：</span><span>{{updateUserData.username}}</span></li>
                </ul>
            </div>
            <div slot="footer">
                <Button type="primary" size="large" @click="modal2=false">取消</Button>
                <Button type="error" size="large" @click="del">确认删除</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import mPagination from "@/components/myPagination";
import { mapState } from "vuex";
import qs from "qs"
export default {
  data() {
    const validatePhoneNumber = (rule, value, callback) => {
      let reg = /^(((0\d{2,3}-)?\d{7,8})|(1[3456789]\d{9}))$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确格式的手机号或电话号"));
      } else {
        callback();
      }
    };

    return {
      isAdd:true,
      tableColumns: [
        { title: "用户名", key: "username", sortable: true},
        {
          title: "角色",
          key: "roleId",
          render: (h, params) => {
            let roleName = "";
            switch (params.row.roleId + "") {
              case "1":
                roleName = "管理员";
                break;
              case "2":
                roleName = "普通用户";
                break;
                default:
                roleName = "回收者";
                break;
            }
            return h("div", [h("span", roleName)]);
          }
        },
        { title: "手机号", key: "phone" },
        { title: "操作", slot: "operate", width: "200" }
      ],
      userDatas: [],
      currentuser: {
        id: "",
        userName: "",
        phone:"",
        password:"888888",
        roleId:null
      },
      updateUserData: {},
      modal1: false,
      modal2: false,
      modal3: false,
      count: 0,
      page: 1,
      pageSize: 10,
      defaultUser: {}, //清空表单项
      ruleValidate: {
        phone: [
          { required: true, message: "请输入手机号！", trigger: "blur" },
          {validator:validatePhoneNumber, trigger: "blur"}
        ],
        username: [
          { required: true, message: "请输入用户名称！", trigger: "blur" }
        ]
      },
      amendLoading:false,
      uploadQuesObj:{
        isImported:false,
        multipartFile:null,
        loading:false
      },
      userTemplateDownload:{
        fileName:"用户导入模板",
        excelType:1//自定义excel类型，1：xlsx；2：xls
      },
    };
  },
  components:{
    mPagination
  },
  computed: {
    ...mapState(["roles","serviceUrl","educationArr"]),
    data1() {
      //章节
      let startNum = (this.page - 1) * this.pageSize;
      let endNum =
        this.page * this.pageSize > this.count
          ? this.count
          : this.page * this.pageSize;
      console.log(startNum, endNum);
      return this.userDatas.slice(startNum, endNum);
    },
  },
  methods: {
    changePage(page) {
      //分页
      this.page = page;
      // this.getUserList();
    },
    getUser(){
       this.$axios.get("/user/findAll").then(res => {
         this.userDatas=res.data;
         this.count=res.data.length;
       })
    },
    toAddUser(){
      this.modal1 = true;
      this.isAdd = true;
    },
    toAmend(row) {
      console.log(row);
      this.currentuser=JSON.parse(JSON.stringify(row));
      this.modal1 = true;
      this.isAdd = false;
    },
    amend() {
      this.$refs["formUserInfo"].validate(valid => {
        if (valid) {
          // if(!this.currentuser["departmentId"]){
          //   this.$Message.error("请检查无误后提交!");
          //   this.mustDepartment="请选择部门"
          //   return false;
          // }
          this.updateUserData = JSON.parse(JSON.stringify(this.currentuser));
          let url=this.isAdd?'user/addUser':"/user/updUser";
          let data=this.isAdd?this.currentuser:this.updateUserData;
          this.amendLoading=true;
          this.$axios.post(url, qs.stringify(data)).then(res => {
              this.amendLoading=false;
            if (res.errorCode==0) {
              this.$Message.success("操作成功!");
              this.modal1 = false;
              this.$refs["formUserInfo"].resetFields();

              this.page = 1;
              this.getUser();
            }
          });
        } else {
          this.amendLoading=false;
          this.$Message.error("请检查无误后提交!");
        }
      });
    },
    cancAmend() {
      this.modal1 = false;
      this.$refs["formUserInfo"].resetFields();
    },
    deleteUser(row) {
      this.updateUserData = JSON.parse(JSON.stringify(row));
      console.log(this.updateUserData)
      this.modal2 = true;
    },
    del() {
      this.$axios
        .post("/user/delUser", qs.stringify({ id: this.updateUserData.id }))
        .then(res => {
          if (res.errorCode == 0) {
            this.$Message.success("操作成功!");
            this.modal2 = false;
            this.page = 1;
            this.getUser();
          }
        });
    },
    resetPwd(row) {
      this.$Modal.confirm({
        title: "密码重置",
        maskClosable: true,
        content:
          "<p>用户" +
          row.userName +
          "登录密码将重置为 888888 ，请确认是否继续。</p>",
        onOk: () => {
          this.$axios
            .post("/user/password", { id: row.id, password: 888888 })
            .then(res => {
              this.$Message.success("重置密码成功!");
              this.page = 1;
              this.getUser();
            });
        }
      });
    }
  },
  created() {
    this.defaultUser = JSON.parse(JSON.stringify(this.currentuser)); //设置表单默认值（清空表单）
    this.page = 1;
    this.getUser();
  }
};
</script>
<style lang="scss" scoped>
.manager-box a {
  color: #fff;
}
.ivu-modal-header p,
.ivu-modal-header-inner {
  font-size: 16px;
}
</style>
